package poo.agendina;

import java.io.*;

import java.util.*;

public abstract class AgendinaAstratta implements Agendina {

	public int size() {
		int c = 0;
		for (Iterator<Nominativo> it = this.iterator(); it.hasNext(); it.next(), c++)
			;
		return c;
	}// size

	public void rimuovi(Nominativo n) {
		Iterator<Nominativo> it = this.iterator();
		while (it.hasNext()) {
			Nominativo y = it.next();
			if (n.equals(y)) {
				it.remove();
				return;
			}
			if (y.compareTo(n) > 0)
				return;
		}
	}// rimuovi

	public void svuota() {
		Iterator<Nominativo> it = iterator();
		while (it.hasNext()) {
			it.next();
			it.remove();
		}
	}// svuota

	public Nominativo cerca(Nominativo n) {
		for (Nominativo x : this) {
			if (x.equals(n))
				return x;
			if (x.compareTo(n) > 0)
				return null;
		}
		return null;
	}// cerca

	public Nominativo cerca(String pref, String tel) {
		for (Nominativo x : this)
			if (x.getPrefisso().equals(pref) && x.getTelefono().equals(tel))
				return x;
		return null;
	}// cerca

	public String toString() {
		StringBuilder sb = new StringBuilder(200);
		for (Nominativo n : this) {
			sb.append(n);
			sb.append("\n");
		}
		return sb.toString();
	}// to String

	public boolean equals(Object x) {
		if (!(x instanceof Agendina))
			return false;
		if (x == this)
			return true;
		Agendina a = (Agendina) x;
		if (size() != a.size())
			return false;
		Iterator<Nominativo> it1 = this.iterator();
		Iterator<Nominativo> it2 = a.iterator();
		while (it1.hasNext()) {
			Nominativo x1 = it1.next(), x2 = it2.next();
			if (!x1.equals(x2))
				return false;
		}
		return true;
	}// equals

	public int hashCode() {
		final int MULT = 83;
		int h = 0;
		for (Nominativo n : this)
			h = h * MULT + n.hashCode();
		return h;
	}// hashCode

	public void salva(String nomeFile) throws IOException {
		PrintWriter pw = new PrintWriter(new FileWriter(nomeFile));
		for (Nominativo x : this)
			pw.println(x);
		pw.close();
	}// salva

	public void ripristina(String nomeFile) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(nomeFile));
		LinkedList<Nominativo> tmp = new LinkedList<>();
		boolean ok = true;
		ciclo: for (;;) {
			String linea = br.readLine();
			if (linea == null)
				break;
			try {
				StringTokenizer st = new StringTokenizer(linea, " -");
				String cog = st.nextToken();
				String nom = st.nextToken();
				String pre = st.nextToken();
				String tel = st.nextToken();
				Nominativo n = new Nominativo(cog, nom, pre, tel);
				tmp.add(n);
			} catch (Exception e) {
				ok = false;
				break ciclo;
			}
		}// for
		if (ok) {
			svuota();
			for (Nominativo x : tmp)
				aggiungi(x);
		}
		br.close();
	}// ripristina
}
